package component.controls.loader
{
	import component.global.manager.EventMgr;
	import component.global.manager.LoaderManager;
	import component.global.utils.ObjectUtil;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	
	[Event(name="complete", type="flash.events.Event")]
	[Event(name="progress", type="flash.events.ProgressEvent")]
	
	public class LoaderQueue extends EventDispatcher
	{
		public function LoaderQueue()
		{
			_loaders = new Vector.<BaseLoader>();
		}
		
		private var _loaders:Vector.<BaseLoader>;
		private var _isLoading:Boolean;
		private var _isComplete:Boolean;
		private var _completeCount:int;
		
		/**
		 * 添加loader到队列 
		 * @param loader BaseLoader 或 继承自 BaseLoader 的子类
		 * @return 返回所添加的loader
		 * 
		 */		
		public function push(loader:BaseLoader):BaseLoader{
			if(_isLoading){
				throw new Error("CUSTOM ERROR: A loader cannot be push into a queue when the queue is started. You may pause or stop the queue firstly or wait the queue complete.");
				return;
			}
			if(loader == null)return loader;
			loader.addEventListener(LoaderEvent.COMPLETE, __onLoaderComplete);
			_loaders.push(loader);
			return loader;
		}
		
		/**
		 * 队列开始进行
		 * 
		 */		
		public function startQueue():void{
			var len:int = _loaders.length;
			for (var i:int = 0; i < len; i++) 
			{
				if(_loaders[i] == null)continue;
				LoaderManager.Instance.startLoad(_loaders[i]);
			}
			if(len == 0){
				dispatchEvent(new LoaderEvent(LoaderEvent.COMPLETE));
			}
		}
		
		/**
		 * 队列内所有loader是否加载完成 
		 * 
		 */		
		public function get isComplete():Boolean{
			return _completeCount == _loaders.length;
		}
		
		public function get progress():int{
			return int(Math.floor(100 * (_completeCount / _loaders.length)));
		}
		
		/**
		 * 重置队列 
		 * 
		 */		
		public function resetQueue():void{
			_completeCount = 0;
			while(_loaders.length>0){
				var loader:BaseLoader = _loaders.shift();
				EventMgr.Instance.removeEvent(loader);
			}
		}
		
		private function __onLoaderComplete(e:LoaderEvent):void{
			e.loader.removeEventListener(LoaderEvent.COMPLETE, __onLoaderComplete);
			_completeCount ++ ;
			dispatchEvent(new LoaderEvent(LoaderEvent.PROGRESS,e.loader));
			if(isComplete){
				resetQueue();
				dispatchEvent(new LoaderEvent(LoaderEvent.QUEUE_COMPLETE));
			}
		}
		
		public function dispose():void{
			ObjectUtil.disposeElements(_loaders);_loaders = null;
		}
	}
}